package com.tfleo.mealssenger;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.apache.http.ParseException;

import com.github.ignition.core.widgets.RemoteImageView;
import com.tfleo.mealssenger.R;
import com.tfleo.mealssenger.adapter.NewsListAdapter;
import com.tfleo.mealssenger.adapter.NoticeGalleryAdapter;
import com.tfleo.mealssenger.object.Food;
import com.tfleo.mealssenger.object.News;
import com.tfleo.mealssenger.object.Notice;
import com.tfleo.mealssenger.service.ChatService;
import com.tfleo.mealssenger.utility.DataFetcher;
import com.tfleo.mealssenger.utility.ImageTools;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.provider.Settings.Secure;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView.ScaleType;

public class NewsActivity extends Activity {
	private static final int NOTICE_ACT = 1;
	
	private LayoutInflater mInflater;
	private ListView vNewsList;
	private RemoteImageView vUserImage;
	private TextView vUserName;
	private TextView vOnlineStatus;
	private TextView vLastCheckinLabel;
	private TextView vLastCheckin;
	private Button vFriendsButton;
	private Button vHangoutButton;
	private Gallery vNoticeGallery;
	
	private int mUserId;
	private String mUserName;
	private String mUserImageUrl;
	private String mLastCheckinPlaceName;
	private int mLastCheckinPlaceId;
	
	private SharedPreferences mSharedPref;
	private SharedPreferences.Editor mPrefEditor; 
	
	private ArrayList<News> mNewsList;
	private NewsListAdapter mNewsAdapter;
	
	private ArrayList<Notice> mNotice;
	private NoticeGalleryAdapter mNoticeAdapter;
	
	public static final int CHECKIN = 1;
	public static final int HAVE = 2;
	
	private Context mContext;
	private static String mAuth;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.social_layout);
		mContext = this;
		mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		mSharedPref = getSharedPreferences(Main.USER_DATA, MODE_PRIVATE);
		mPrefEditor = mSharedPref.edit();
		mAuth = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID); //for authentication
		
		mUserId = mSharedPref.getInt(Main.USER_ID, 0);
		mUserName = mSharedPref.getString(Main.USER_NAME, "Kirunavaara");
		mUserImageUrl = Main.SERVER_URL + "img/user/" + mSharedPref.getString(Main.USER_IMAGE, Main.SERVER_URL + "img/user/0.jpg");
		mLastCheckinPlaceId = mSharedPref.getInt(Main.LAST_CHECKIN_PLACEID, 0);
		mLastCheckinPlaceName = mSharedPref.getString(Main.LAST_CHECKIN_PLACENAME, "");
		
		
		if(mUserId == 0) {
			Toast.makeText(mContext, "Error: Invalid user id!", Toast.LENGTH_SHORT).show();
			finish();
		}
		
		vUserImage = (RemoteImageView) findViewById(R.id.img);
		vUserImage.setImageUrl(mUserImageUrl);
		vUserImage.loadImage();
		
		vUserName = (TextView) findViewById(R.id.name);
		vUserName.setText(mUserName);
		
		vOnlineStatus = (TextView) findViewById(R.id.online_status);
		
		vLastCheckin = (TextView) findViewById(R.id.last_checkin);
		vLastCheckinLabel = (TextView) findViewById(R.id.last_checkin_label);
		
		if(mLastCheckinPlaceId != 0) {
			vLastCheckinLabel.setVisibility(View.VISIBLE);
			vLastCheckin.setText(mLastCheckinPlaceName);
		}
		
		vNewsList = (ListView) findViewById(R.id.news_list);
		vNoticeGallery = (Gallery) findViewById(R.id.notice_gallery);
		
		FetchNoticeTask task1 = new FetchNoticeTask();
		task1.execute(mUserId);
		
		vFriendsButton = (Button) findViewById(R.id.view_friends_btn);
		vFriendsButton.setOnClickListener(new OnClickListener() {
	        public void onClick(View v) {
	        	Intent i = new Intent(NewsActivity.this, FriendBrowseActivity.class);
	        	i.putExtra("id", mUserId);
            	startActivity(i); 
	        }
	    });
		
		vHangoutButton = (Button) findViewById(R.id.hangout_btn);
		vHangoutButton.setOnClickListener(new OnClickListener() {
	        public void onClick(View v) {
	        	Intent i = new Intent(NewsActivity.this, HangoutBrowseActivity.class);
            	startActivity(i); 
	        }
	    });
        
        FetchNewsTask task2 = new FetchNewsTask();
		task2.execute();
		
		if(mSharedPref.getBoolean(Main.ONLINE, false)) {
			vOnlineStatus.setText("online");
			vOnlineStatus.setTextColor(getResources().getColor(R.color.green));
		} else {
			vOnlineStatus.setText("offline");
			vOnlineStatus.setTextColor(getResources().getColor(R.color.red));
		}

	}
	
	@Override
	public void onResume() {
		super.onResume();
		if(mLastCheckinPlaceId != 0) {
			vLastCheckinLabel.setVisibility(View.VISIBLE);
			vLastCheckin.setText(mLastCheckinPlaceName);
		}
	}
	
	private class FetchNewsTask extends AsyncTask<Void, Void, Boolean> {
		private ProgressDialog mProgressDialog;
		@Override    
	    protected void onPreExecute() {       
	        super.onPreExecute();
	        mProgressDialog = new ProgressDialog(mContext);
	        mProgressDialog.setMessage("Loading...");
	        mProgressDialog.setCancelable(false);
	        mProgressDialog.setIndeterminate(true);
	        mProgressDialog.show();
	    }
		
		@Override
		protected Boolean doInBackground(Void... v) {
			mNewsList = DataFetcher.fetchNews(mUserId, mAuth);
			if(mNewsList == null) {
				return false;
			}
			return true;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				mNewsAdapter = new NewsListAdapter(mContext,
						R.layout.news_entry, R.id.name, mNewsList, mInflater);
				vNewsList.setAdapter(mNewsAdapter);
				mProgressDialog.dismiss();
    		} else {
    			Toast.makeText(mContext, "Error: Connection with server failed!", Toast.LENGTH_SHORT).show();
    			mProgressDialog.dismiss();
    		}
	    }
		
	}
	
	private class FetchNoticeTask extends AsyncTask<Integer, Void, Boolean> {
		private ProgressDialog mProgressDialog;
		@Override    
	    protected void onPreExecute() {       
	        super.onPreExecute();
	        mProgressDialog = new ProgressDialog(mContext);
	        mProgressDialog.setMessage("Loading...");
	        mProgressDialog.setCancelable(false);
	        mProgressDialog.setIndeterminate(true);
	        mProgressDialog.show();
	    }
		
		@Override
		protected Boolean doInBackground(Integer... credential) {
			int userId = credential[0];
			
			mNotice = DataFetcher.fetchNotice(userId, mAuth);
			if(mNotice == null) {
				return false;
			}
			return true;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				mNoticeAdapter = new NoticeGalleryAdapter(mContext, mNotice, mInflater);
				vNoticeGallery.setAdapter(mNoticeAdapter);
				vNoticeGallery.setCallbackDuringFling(false);
				vNoticeGallery.setSpacing(10);
				vNoticeGallery.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						Intent i;
						Notice n = mNotice.get(position);
						switch(n.type) {
						case 1: //friend request
							i = new Intent(NewsActivity.this, UserActivity.class);
							i.putExtra(UserActivity.WHO, UserActivity.NOT_FRIEND);
							break;
						case 2: //food share
							i = new Intent(NewsActivity.this, FoodActivity.class);
							i.putExtra("ack", true);
							break;
						case 3: //hangout
							i = new Intent(NewsActivity.this, HangoutActivity.class);
							break;
						default: //suggest something
							//i = new Intent(NewsActivity.this, SuggestionActivity.class);
							return;
						}
						
						i.putExtra("id", n.objectId);
						startActivityForResult(i, NOTICE_ACT); 
					}
				});
				mProgressDialog.dismiss();
    		} else {
    			Toast.makeText(mContext, "Error: Connection with server failed!", Toast.LENGTH_SHORT).show();
    			mProgressDialog.dismiss();
    		}
	    }
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == NOTICE_ACT) {  
        	FetchNoticeTask task = new FetchNoticeTask();
        	task.execute(mUserId);
        }
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.social_menu, menu);
		return result;
	}
    
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
    	Intent i;
		switch(item.getItemId()) {
		
		case R.id.edit_profile:
			i = new Intent(this, EditProfileActivity.class);
			startActivity(i);
			return true;
		case R.id.refresh:
			FetchNoticeTask task1 = new FetchNoticeTask();
			task1.execute(mUserId);
			
			FetchNewsTask task2 = new FetchNewsTask();
			task2.execute();
			return true;
		case R.id.chat_status:
			if(mSharedPref.getBoolean(Main.ONLINE, false)) {
				mPrefEditor.putBoolean(Main.ONLINE, false); 
				mPrefEditor.commit();
				vOnlineStatus.setText("offline");
				vOnlineStatus.setTextColor(getResources().getColor(R.color.red));
				//stop chat service
				ChatService.actionStop(getApplicationContext());
			} else {
				mPrefEditor.putBoolean(Main.ONLINE, true); 
				mPrefEditor.commit();
				vOnlineStatus.setText("online");
				vOnlineStatus.setTextColor(getResources().getColor(R.color.green));
				//start chat service
				ChatService.actionStart(getApplicationContext());
			}
			return true;
		case R.id.preferences:
			showPreferences();
			return true;
		case R.id.info:
			showInfo();
			return true;
		case R.id.logout:
			i = new Intent(this, LoginActivity.class);
			i.putExtra("logout", true);
			startActivity(i);
			finish();
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}
    
    private void showPreferences() {
		Intent i = new Intent(this, SettingsActivity.class);
		startActivity(i);
	}
    
    private void showInfo() {
		Intent i = new Intent(this, InfoActivity.class);
		startActivity(i);
	}
}
